package com.android.common.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.lang.ref.WeakReference;

/**
  * 执行数据库操作
 */
public class AssetsDBOperation {
    private final AssetsDBCreator mAssetsDBCreator;
    private SQLiteDatabase mDB;

    private static AssetsDBOperation mDatabaseOperator;

    public static AssetsDBOperation getInstance(Context context){
        if (null == mDatabaseOperator)
            mDatabaseOperator = new AssetsDBOperation(context);
        return mDatabaseOperator;
    }
    private AssetsDBOperation(Context context) {
        WeakReference<Context> weakContext = new WeakReference<>(context);
        mAssetsDBCreator = new AssetsDBCreator(weakContext.get());
    }
    public void openWritableDatabase() {
        mDB = mAssetsDBCreator.getWritableDatabase();
    }

    public void openReadableDatabase() {
        mDB = mAssetsDBCreator.getReadableDatabase();
    }

    public void closeDatabase() {
        if (mDB.isOpen()){
            mAssetsDBCreator.close();
        };
    }

    public long insert(String table, String nullColumnHack, ContentValues values) {
        long result = -1;
        try{
            openWritableDatabase();
            result = mDB.insert(table,nullColumnHack,values);
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            closeDatabase();
        }
        return result;
    }
    public Cursor query(String table, String[] columns, String selection,
                        String[] selectionArgs, String groupBy, String having,
                        String orderBy) {
        Cursor cursor = null;
        try{
            openReadableDatabase();
            cursor = mDB.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return cursor;
    }
    public int delete(String table, String whereClause, String[] whereArgs) {
        int result = 0;
        try{
            openWritableDatabase();
            result = mDB.delete(table, whereClause, whereArgs);
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            closeDatabase();
        }
        return result;
    }

    public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
        int result = 0;
        try{
            openWritableDatabase();
            result = mDB.update(table, values, whereClause, whereArgs);
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            closeDatabase();
        }
        return result;
    }
}
